package com.hmbe.controller;

import com.hmbe.utils.MinIOUtils;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/minio/file")
public class FileController {

    @Autowired
    private MinIOUtils minIOUtils;

    /**
     * 创建桶
     */
    @PostMapping("/bucket/{bucketName}")
    public ResponseEntity<String> createBucket(@PathVariable String bucketName) {
        try {
            minIOUtils.createBucket(bucketName);
            return ResponseEntity.ok("Bucket created successfully: " + bucketName);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to create bucket: " + e.getMessage());
        }
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload/{bucketName}")
    public ResponseEntity<String> uploadFile(
            @PathVariable String bucketName,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName) {

        try {
            //如果未指定桶名，则使用"default"桶"
            if (bucketName == null || bucketName.isEmpty()) {
                bucketName = "default";
                minIOUtils.createBucket(bucketName);
            }
            if (minIOUtils.bucketExists((bucketName))) {
                minIOUtils.uploadFile(bucketName, fileName, file);
                //上传成功,返回url
                String url = minIOUtils.getPresignedObjectUrl(bucketName, fileName, 7  );
                System.out.println("url = " + url);
                return ResponseEntity.ok("File uploaded successfully: " + url);
            } else {
                minIOUtils.createBucket(bucketName);
            }
            // 如果未指定文件名，则使用原文件名
            String objectName = fileName != null ? fileName : file.getOriginalFilename();
            minIOUtils.uploadFile(bucketName, objectName, file);
            //上传成功,返回url
            String url = minIOUtils.getPresignedObjectUrl(bucketName, fileName, 7);
            System.out.println("url = " + url);
            return ResponseEntity.ok("File uploaded successfully: " + url);
        } catch (Exception e) {
            log.error("Failed to upload file: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to upload file: " + e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{bucketName}/{fileName}")
    public ResponseEntity<byte[]> downloadFile(
            @PathVariable String bucketName,
            @PathVariable String fileName) {

        try (InputStream stream = minIOUtils.getFileStream(bucketName, fileName)) {
            byte[] bytes = stream.readAllBytes();

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));

            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Failed to download file: " + e.getMessage()).getBytes());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/{bucketName}/{fileName}")
    public ResponseEntity<String> deleteFile(
            @PathVariable String bucketName,
            @PathVariable String fileName) {

        try {
            minIOUtils.deleteFile(bucketName, fileName);
            return ResponseEntity.ok("File deleted successfully: " + fileName);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to delete file: " + e.getMessage());
        }
    }

    /**
     * 获取文件访问URL
     */
    @GetMapping("/url/{bucketName}/{fileName}")
    public ResponseEntity<String> getFileUrl(
            @PathVariable String bucketName,
            @PathVariable String fileName,
            @RequestParam(defaultValue = "7") int days) {

        try {
            String url = minIOUtils.getPresignedObjectUrl(bucketName, fileName, days);
            return ResponseEntity.ok(url);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to get file url: " + e.getMessage());
        }
    }

    /**
     * 列出所有桶
     */
    @GetMapping("/buckets")
    public ResponseEntity<List<String>> listBuckets() {
        try {
            List<String> buckets = minIOUtils.listBuckets();
            return ResponseEntity.ok(buckets);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 列出桶中的所有文件
     */
    @GetMapping("/list/{bucketName}")
    public ResponseEntity<List<String>> listFiles(@PathVariable String bucketName) {
        try {
            List<String> files = minIOUtils.listObjects(bucketName);
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
